package org.batatasframework.support.database.sql;

import org.batatasframework.support.database.JoinType;
import org.batatasframework.support.database.metadatas.TableMetadata;

/**
 * <pre>
 * 主表关联的关联表，关联表最主要的就需要有一个字段，指定如果与主表进行关联
 * </pre>
 * <pre>
 * 在关联表里，需要指定两个字段，一个是主表的字段，一个是被关联表的字段；
 * 这两个字段只被当成是关联字段，并不一定是主键或外键等约束的
 * </pre>
 * @author jackson
 *
 */
public class TableRuntimeJoin extends TableInstance{
	
	private final TableRuntimeMaster masterTable;
	
	private JoinType type = JoinType.LEFT;
	
	/** 被关联表需要被关联的字段，即:x.masterField=y.joinField的情况 */
	private String joinField;
	/** 被关联的目标表 */
	private final TableInstance targetTable;
	/** 主表需要拿出来关联的字段 */
	private String masterField;
	
	TableRuntimeJoin(TableRuntimeMaster masterTable, TableMetadata joinTable) throws Exception{
		this(masterTable, masterTable, joinTable);
	}

	TableRuntimeJoin(TableRuntimeMaster masterTable, TableInstance targetTable, TableMetadata joinTable) throws Exception{
		super(joinTable, masterTable.newAliasName());
		//是可以在这个时候才生成关联表的别名的
		this.masterTable = masterTable;
		this.targetTable = targetTable;
	}
	
	public TableRuntimeJoin on(JoinType type, String masterField, String joinField){
		this.type = type;
		this.masterField = masterField;
		this.joinField = joinField;
		return this;
	}

	public TableRuntimeJoin on(String joinField){
		return on(JoinType.LEFT, targetTable.getTableMetadata().getPrimaryKey(), joinField);
	}
	
	public String getJoinType(){
		return type.getValue();
	}
	
	public String getJoinField() {
		return joinField;
	}
	
	public String getMasterField() {
		return masterField;
	}
	
	public String getTargetAlias() {
		return targetTable.getAlias();
	}
	
	public TableRuntimeMaster getMasterTable() {
		return masterTable;
	}
}
